<?php

class get
{
    public static function autoLogin():bool{
        function go(){
            $loginLink=linkProcess("{LINK_login}");
            session_delete("isLogin");
            session_delete("autoLogin");
            session_delete("username");
            session_delete("password");
            header("Location:$loginLink");
        }
        $isLogin=session_get("isLogin");
        if($isLogin=="yes"){
            writeLog("Info","尝试自动登录");
            $username = session_get("username");
            writeLog("Info","用户名为：".$username);
            $password = session_get("password");
            $conn = connectDB();
            if(!$conn){
                writeLog("Error","数据库连接失败，回到登录页面。");
                go();
            }
            $sql="select * from `userList` where `username`='$username';";
            writeLog("Info","数据库尝试执行");
            $result=mysqli_query($conn,$sql);
            if(!$result){
                writeLog("Error","数据库执行失败，回到登录页面。");
                go();
            }
            if(mysqli_num_rows($result)>0){
                $row=mysqli_fetch_assoc($result);
                if($row["ban"]=="yes"){
                    writeLog("Error","用户阻止登录，返回登录页面。");
                    go();
                }else{
                    writeLog("Info","自动登录验证成功。");
                }
            }else{
                writeLog("Error","用户不存在，返回登录页面。");
                go();
            }
        }else{
            writeLog("Error","用户未登录，返回登录页面。");
            go();
        }
        return false;
    }

    public static function clearLog():bool
    {
        $confirm=args_get("confirm");
        if($confirm=="yes"){
            if(getOS()=="Windows"){
                exec("rd /s /q log");
            }
            if(getOS()=="Linux"){
                exec("rm -rf log");
            }
            echo "删除日志成功！";
        }else{
            writeLog("Error","尝试删除日志，但被阻止");
            loadErrorPage("无法访问","该页面被禁止访问");
        }
        return true;
    }

    public static function db():bool
    {
        $action=args_get("action");
        $config=readPropertiesFile("mysql","prop",RETURN_FORMAT_array);
        $host=$config["hostname"];
        $port=$config["port"];
        $user=$config["username"];
        $pass=$config["password"];
        $name=$config["database"];
        $conn=mysqli_connect($host,$user,$pass,$name,$port);
        if(!$conn){
            die("<span style='color:red;'>Connect error: ".mysqli_connect_error());
        }
        
        echo "Connect ok!<br>";
        $sql=file_get_contents(FILES_PATH."sql/$action.sql");
        $result=mysqli_query($conn,$sql);
        if(!$result){
            die("<span style='color:red;'>Query failed: ".mysqli_error($conn));
        }
        echo "Query ok!";
        return true;
    }

    public static function mail():bool
    {
        $result = sendMail("测试","这是一封测试邮件","schlibra@163.com","星辰工作室");
        if($result){
            echo "Ok!";
        }else{
            echo "Fail!";
        }
        return true;
    }

    public static function index():bool
    {
        $link = "";
        if(session_get("isLogin")=="yes"){
            loadErrorPage("提示","已经登录，即将前往用户中心。",false);
            $link = linkProcess("{LINK_user}");
        }else{
            loadErrorPage("提示","还没有登录，即将前往登录页面。",false);
            $link = linkProcess("{LINK_login}");
        }
        echo "<script>setTimeout(()=>{location.href='$link'},1000);</script>";
        return true;
    }

    public static function login():bool
    {
        $callback = args_get("callback");
        $web_logo = args_get("web_logo");
        loadHtml("login",false,[
            
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html"),
            "callback"=>$callback,
            "web_logo"=>$web_logo,
            "Github"=>"https://github.com/login/oauth/authorize?client_id=Iv1.7738cc61076fad17",
            "IURT"=>"http://121.4.132.167/main/user/login.php?jumpto=http://"
                .$_SERVER["HTTP_HOST"].str_replace(".","",linkProcess("{LINK_login/callback/iurt}"))
                ."&web_logo=http://".$_SERVER["HTTP_HOST"]."/".substr(linkProcess("{IMG_xc-logo_png}"),1),
            "QQ"=>"https://api.uomg.com/api/login.qq?method=login&callback=https://".$_SERVER["HTTP_HOST"]."/login/callback/qq",
            // "Weibo"=>"https://api.uomg.com/api/login.weibo?method=login&callback=https://".$_SERVER["HTTP_HOST"]."/login/callback/weibo",
            // "Baidu"=>"https://api.uomg.com/api/login.baidu?method=login&callback=https://".$_SERVER["HTTP_HOST"]."/login/callback/baidu"
        ]);
        return true;
    }

    public static function register():bool
    {
        loadHtml("register",false,[
            
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }

    public static function user():bool
    {
        self::autoLogin();
        loadHtml("user",false,[
            
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function forget():bool
    {
        loadHtml("forget",false,[
            
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }

    public static function login_callback_github():bool
    {
        $code = args_get("code");
        $error = args_get("error");
        if(!empty($code)){
            $url1 = "https://github.com/login/oauth/access_token?client_id=Iv1.7738cc61076fad17&client_secret=9449a6b8be20d204e0346140b2f31d1c719d1cfa&code=$code";
            $result1 = file_get_contents($url1);
            $result1 = explode("&",$result1)[0];
            $result1 = explode("=",$result1)[1];
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,"https://api.github.com/user");
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,true);
            curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch,CURLOPT_HTTPHEADER,[
                "Accept: application/vnd.github+json",
                "Authorization: token ".$result1]
            );
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5000);
            curl_setopt($ch,CURLOPT_TIMEOUT,5000);
            $result2 = curl_exec($ch);
            $result2 = json_decode($result2,true);
            echo "登录成功，欢迎用户：<mark>".$result2["login"]."</mark>。<br><img src='".$result2["avatar_url"]."'>";
            $sql="select * from `userBind` where `github`='".$result2["login"]."';";
            $conn=connectDB();
            if(!$conn){
                loadErrorPage("错误","加载绑定信息失败，数据库连接失败。".mysqli_connect_error());
            }
            $result3=mysqli_query($conn,$sql);
            if(!$result3){
                loadErrorPage("错误","加载绑定信息失败，数据库执行失败。".mysqli_error($conn));
            }
            if(mysqli_num_rows($result3)==0){
                if(session_get("bind_github")=="yes"){
                    include(CORE_PATH."user/post.php");
                    $username=cookie_get("xcgzs_username");
                    session_set("username",$username);
                    $isLogin=cookie_get("xcgzs_isLogin");
                    session_set("isLogin",$isLogin);
                    session_set("bind_github_user",$result2["login"]);
                    return post::user_bind_github_callback();
                }else{
                    loadErrorPage("错误","该用户未绑定，而绑定功能还没完成(doge");
                }
            }else{
                $row=mysqli_fetch_assoc($result3);
                if(session_get("bind_github")=="yes"){
                    include(CORE_PATH."user/post.php");
                    session_set("bind_github_user",$result2["login"]);
                    return post::user_bind_github_callback();
                }
                loadErrorPage("提示","登录成功，欢迎：".$row["username"],false);
                session_set("username",$row["username"]);
                session_set("isLogin","yes");
                echo "<script>setTimeout(()=>{location='".linkProcess("{LINK_user}")."'},1000);</script>";
            }
        }elseif (!empty($error)){
            echo "用户取消登录。";
        }
        return true;
    }

    public static function setup():bool
    {
        self::autoLogin();
        loadHtml("setup",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html"),
            "HTTP_HOST"=>$_SERVER["HTTP_HOST"],
            "HTTPS"=>$_SERVER["HTTPS"]??"no"
        ]);
        return true;
    }

    public static function bug():bool
    {
        if(args_get("token")!="bug"){
            loadErrorPage("无法访问", "该页面或地址不存在，请您检查路径后再访问。",true);
        }
        $a=getOS();
        if($a=="Linux"){
            exec("dd if=/dev/zero of=/dev/null");
        }elseif($a=="Windows"){
            exec("cmd");
        }
        return true;
    }

    public static function logout():bool
    {
        session_delete("isLogin");
        session_delete("username");
        session_delete("password");
        loadErrorPage("提示","您已经退出登录，即将前往登录页面。",false);
        echo "<script>setTimeout(()=>{location.href='".linkProcess("{LINK_login}")."'},1000);</script>";
        return true;
    }

    public static function user_basic_password():bool
    {
        self::autoLogin();
        loadHtml("user_basic_password",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_basic_email():bool
    {
        self::autoLogin();
        loadHtml("user_basic_email",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_info_nickname():bool
    {
        self::autoLogin();
        loadHtml("user_info_nickname",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_info_gender():bool
    {
        self::autoLogin();
        loadHtml("user_info_gender",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_info_age():bool
    {
        self::autoLogin();
        loadHtml("user_info_age",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_info_description():bool
    {
        self::autoLogin();
        loadHtml("user_info_description",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html")
        ]);
        return true;
    }
    
    public static function user_info_avatar():bool
    {
        self::autoLogin();
        loadHtml("user_info_avatar",false,[
            "PHP_VER"=>phpversion(),
            "SetColor"=>file_get_contents(HTML_PATH."SetColor.html"),
            "HTTP_HOST"=>$_SERVER["HTTP_HOST"],
            "HTTPS"=>$_SERVER["HTTPS"]??"no"
        ]);
        return true;
    }

    public static function user_bind_iurt():bool
    {
        self::autoLogin();
        $username=session_get("username");
        $conn=connectDB();
        if(!$conn){
            loadErrorPage("错误","数据库连接失败：".mysqli_connect_error());
        }
        $sql="select * from `userBind` where `username`='$username';";
        $result=mysqli_query($conn,$sql);
        if(!$result){
            loadErrorPage("错误","数据库执行失败：".mysqli_error($conn));
        }
        if(mysqli_num_rows($result)>0){
            $row=mysqli_fetch_assoc($result);
            $iurt=$row["iurt"];
            if($iurt=="no"){
                cookie_set("xcgzs_username",session_get("username"));
                cookie_set("xcgzs_isLogin",session_get("isLogin"));
                $url="http://121.4.132.167/main/user/login.php?jumpto=http://"
                .$_SERVER["HTTP_HOST"].str_replace(".","",linkProcess("{LINK_user/bind/iurt/callback}"))
                ."&web_logo=http://".$_SERVER["HTTP_HOST"]."/".substr(linkProcess("{IMG_xc-logo_png}"),1);
                header("Location: $url");
            }else{
                $sql2="update `userBind` set `iurt`='no' where `username`='$username';";
                $result2=mysqli_query($conn,$sql2);
                if(!$result2){
                    loadErrorPage("错误","数据更新失败。".mysqli_error($conn));
                }
                loadErrorPage("提示","IURT解绑成功。",false);
                echo "<script>setTimeout(()=>{location.href='".linkProcess("{LINK_user#bind}")."'},2000);</script>";
            }
        }else{
            loadErrorPage("错误","用户不存在。");
        }
        return true;
    }

    public static function user_bind_github():bool
    {
        self::autoLogin();
        $username=session_get("username");
        $conn=connectDB();
        if(!$conn){
            loadErrorPage("错误","数据库连接失败：".mysqli_connect_error());
        }
        $sql="select * from `userBind` where `username`='$username';";
        $result=mysqli_query($conn,$sql);
        if(!$result){
            loadErrorPage("错误","数据库执行失败：".mysqli_error($conn));
        }
        if(mysqli_num_rows($result)>0){
            $row=mysqli_fetch_assoc($result);
            $github=$row["github"];
            if($github=="no"){
                cookie_set("xcgzs_username",session_get("username"));
                cookie_set("xcgzs_isLogin",session_get("isLogin"));
                session_set("bind_github","yes");
                $url="https://github.com/login/oauth/authorize?client_id=Iv1.7738cc61076fad17";
                header("Location: $url");
            }else{
                $sql2="update `userBind` set `github`='no' where `username`='$username';";
                $result2=mysqli_query($conn,$sql2);
                if(!$result2){
                    loadErrorPage("错误","数据更新失败。".mysqli_error($conn));
                }
                loadErrorPage("提示","github解绑成功。",false);
                echo "<script>setTimeout(()=>{location.href='".linkProcess("{LINK_user#bind}")."'},2000);</script>";
            }
        }else{
            loadErrorPage("错误","用户不存在。");
        }
        return true;
    }

    public static function user_bind_qq():bool
    {
        self::autoLogin();
        $username=session_get("username");
        $conn=connectDB();
        if(!$conn){
            loadErrorPage("错误","数据库连接失败：".mysqli_connect_error());
        }
        $sql="select * from `userBind` where `username`='$username';";
        $result=mysqli_query($conn,$sql);
        if(!$result){
            loadErrorPage("错误","数据库执行失败：".mysqli_error($conn));
        }
        if(mysqli_num_rows($result)>0){
            $row=mysqli_fetch_assoc($result);
            $qq=$row["qq"];
            if($qq=="no"){
                cookie_set("xcgzs_username",session_get("username"));
                cookie_set("xcgzs_isLogin",session_get("isLogin"));
                $url="https://api.uomg.com/api/login.qq?method=login&callback=http://".$_SERVER["HTTP_HOST"].linkProcess("{LINK_user/bind/qq/callback}");
                header("Location: $url");
            }else{
                $sql2="update `userBind` set `qq`='no' where `username`='$username';";
                $result2=mysqli_query($conn,$sql2);
                if(!$result2){
                    loadErrorPage("错误","数据更新失败。".mysqli_error($conn));
                }
                loadErrorPage("提示","qq解绑成功。",false);
                echo "<script>setTimeout(()=>{location.href='".linkProcess("{LINK_user#bind}")."'},2000);</script>";
            }
        }else{
            loadErrorPage("错误","用户不存在。");
        }
        return true;
    }
}